package com.ruoyi.web.controller.custom;
import javax.servlet.http.HttpServletResponse;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.CustomerType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.domain.from.*;
import com.ruoyi.system.domain.vo.CrmCustomerInfoDetail;
import com.ruoyi.system.domain.vo.CustomerInfoPageVo;
import com.ruoyi.system.service.ICrmCustomerUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.CrmCustomerInfo;
import com.ruoyi.system.service.ICrmCustomerInfoService;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 客户Controller
 * 
 * @author yangsen
 * @date 2023-05-10
 */
@RestController
@RequestMapping("/crmcustomer/info")
@Api(value = "意向客户",tags = "意向客户")
@Slf4j
public class CrmCustomerInfoController extends BaseController {
    @Autowired
    private ICrmCustomerInfoService crmCustomerInfoService;

    @Autowired
    private ICrmCustomerUserService iCrmCustomerUserService;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询客户列表
     */
    @PreAuthorize("@ss.hasPermi('custom:info:list')")
    @ApiOperation(value = "查询客户列表",notes = "查询客户列表")
    @PostMapping("/list")
    public R<CustomerInfoPageVo> list(@RequestBody CrmCustomerInfoQuery crmCustomerInfoQuery) {
        return crmCustomerInfoService.selectCrmCustomerInfoList(crmCustomerInfoQuery,CustomerType.INTENDEDCUSTOMERS.getCustomerTypeCode());
    }

    /**
     * 导出客户列表
     */
    @PreAuthorize("@ss.hasPermi('custom:info:export')")
    @Log(title = "意向客户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,@RequestBody CrmCustomerInfoQuery crmCustomerInfoQuery) {
        crmCustomerInfoService.exportCrmCustomerInfo(response,CustomerType.INTENDEDCUSTOMERS.getCustomerTypeCode(), crmCustomerInfoQuery);
    }

    /**
     * 获取客户详细信息
     */
    @PreAuthorize("@ss.hasPermi('custom:info:query')")
    @ApiOperation(value = "获取客户详细信息详情",notes = "获取客户详细信息详情")
    @ApiImplicitParam(name = "customerId", value = "客户ID", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
    @GetMapping(value = "/{customerId}")
    public R<CrmCustomerInfoDetail>  getInfo(@PathVariable("customerId") Long customerId) {
        return crmCustomerInfoService.selectCrmCustomerInfoBycustomerId(customerId);
    }

    /**
     * 新增客户
     */
    @PreAuthorize("@ss.hasPermi('custom:info:add')")
    @Log(title = "意向客户", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增意向客户",notes = "新增意向客户")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CrmCustomerAdd crmCustomerAdd) {
        return crmCustomerInfoService.addCrmCustomerInfo(crmCustomerAdd,CustomerType.INTENDEDCUSTOMERS.getCustomerTypeCode());
    }

    /**
     * 修改客户
     */
    @PreAuthorize("@ss.hasPermi('custom:info:edit')")
    @Log(title = "意向客户", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改意向客户",notes = "修改意向客户")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CrmCustomerUpdate crmCustomerUpdate) {
        return crmCustomerInfoService.updateCrmCustomerInfoNew(crmCustomerUpdate);
    }

    /**
     * 删除客户
     */
    @PreAuthorize("@ss.hasPermi('custom:info:remove')")
    @Log(title = "意向客户", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除意向客户",notes = "删除意向客户")
    @ApiImplicitParam(name = "customerId", value = "客户ID", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
	@DeleteMapping("/{customerId}")
    public AjaxResult remove(@PathVariable Long customerId) {
        return crmCustomerInfoService.deleteCrmCustomerInfoBycustomerIds(customerId);
    }

    @PreAuthorize("@ss.hasPermi('custom:info:removelist')")
    @Log(title = "意向客户", businessType = BusinessType.DELETE)
    @ApiOperation(value = "批量删除意向客户",notes = "批量删除意向客户")
//    @ApiImplicitParam(name = "customerIds", value = "客户ID集合", required = true, dataType = "list", paramType = "path", dataTypeClass = Long.class)
    @DeleteMapping("/list")
    public AjaxResult remove(@RequestBody DeleteList deleteList) {
        return crmCustomerInfoService.deleteCrmCustomerInfoBycustomerIdsAll(deleteList);
    }

    /**
     * 类型转换
     */
    @PreAuthorize("@ss.hasPermi('custom:info:exchange')")
    @Log(title = "意向客户", businessType = BusinessType.OTHER)
    @ApiOperation(value = "转换意向客户",notes = "转换意向客户")
    @ApiImplicitParam(name = "customerId", value = "客户ID", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
    @GetMapping("/exchange/{customerId}")
    public AjaxResult exchange(@PathVariable Long customerId) {
        return crmCustomerInfoService.exchangeCrmCustomerInfo(customerId);
    }


    /**
     * 上传合同
     */
    @Log(title = "意向客户", businessType = BusinessType.OTHER)
    @ApiOperation(value = "合同上传",notes = "合同上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "customerId", value = "客户ID", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
    })
    @PostMapping("/uploads/{customerId}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult uploads(@PathVariable Long customerId,@RequestPart("file")MultipartFile file) {
        CrmCustomerInfo crmCustomerInfo = crmCustomerInfoService.getById(customerId);
        if (ObjectUtil.isNull(crmCustomerInfo)){
            return AjaxResult.error("客户信息不存在");
        }
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            String substring = fileName.substring(15);
            ajax.put("url", url);
            ajax.put("fileName", substring);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            crmCustomerInfo.setImportFlag(1L);
            crmCustomerInfo.setFileName(substring);
            crmCustomerInfo.setOriginalFilename(file.getOriginalFilename());
            crmCustomerInfoService.updateById(crmCustomerInfo);
            return ajax;
        }
        catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    @Log(title = "意向客户", businessType = BusinessType.OTHER)
    @ApiOperation(value = "合同下载",notes = "合同下载")
    @ApiImplicitParam(name = "customerId", value = "客户ID", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
    @GetMapping("/download/{customerId}")
    @Transactional(rollbackFor = Exception.class)
    public void download(@PathVariable Long customerId,HttpServletResponse response) {
        CrmCustomerInfo crmCustomerInfo = crmCustomerInfoService.getById(customerId);
        if (ObjectUtil.isNull(crmCustomerInfo)){
           throw new RuntimeException("客户不存在");
        }
        String fileName=crmCustomerInfo.getFileName();
        try {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = crmCustomerInfo.getOriginalFilename();
            String filePath = RuoYiConfig.getUploadPath() + fileName;
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        }
        catch (Exception e) {
            log.error("下载文件失败", e);
        }

    }

    @PreAuthorize("@ss.hasPermi('custom:info:import')")
    @PostMapping("/importData/{customerId}")
    @Log(title = "意向客户", businessType = BusinessType.IMPORT)
    @ApiImplicitParam(name = "customerId", value = "客户ID", required = true, dataType = "long", paramType = "path", dataTypeClass = Long.class)
    @ApiOperation(value = "批量导入",notes = "批量导入")
    public AjaxResult importData(@PathVariable Long customerId,@RequestPart("files")List<MultipartFile> files) throws Exception {
        return iCrmCustomerUserService.crmCustomerUserImportExcel(customerId,files);
    }

    @PostMapping("/reptileAll")
    @Log(title = "意向客户", businessType = BusinessType.OTHER)
    @PreAuthorize("@ss.hasPermi('custom:info:reptileAll')")
    @ApiOperation(value = "全部筛查",notes = "爬虫按钮")
    public R reptileAll(@RequestBody ReptileFrom reptileFrom){
        reptileFrom.setReptileType("all");
        return iCrmCustomerUserService.reptile(reptileFrom);
    }

    @PostMapping("/reptileUnemployment")
    @Log(title = "意向客户", businessType = BusinessType.OTHER)
    @ApiOperation(value = "失业校验",notes = "爬虫按钮")
    @PreAuthorize("@ss.hasPermi('custom:info:reptileUnemployment')")
    public R reptileUnemployment(@RequestBody ReptileFrom reptileFrom){
        reptileFrom.setReptileType("unemployment");
        return iCrmCustomerUserService.reptile(reptileFrom);
    }

    @PostMapping("/reptileIdentity")
    @Log(title = "意向客户", businessType = BusinessType.OTHER)
    @ApiOperation(value = "身份校验",notes = "爬虫按钮")
    @PreAuthorize("@ss.hasPermi('custom:info:reptileIdentity')")
    public R reptileIdentity(@RequestBody ReptileFrom reptileFrom){
        reptileFrom.setReptileType("identity");
        return iCrmCustomerUserService.reptile(reptileFrom);
    }

    @PostMapping("/reptileRetired")
    @Log(title = "意向客户", businessType = BusinessType.OTHER)
    @ApiOperation(value = "退役校验",notes = "爬虫按钮")
    @PreAuthorize("@ss.hasPermi('custom:info:reptileRetired')")
    public R reptileRetired(@RequestBody ReptileFrom reptileFrom){
        reptileFrom.setReptileType("retired");
        return iCrmCustomerUserService.reptile(reptileFrom);
    }

    @PostMapping("/reptilallchick")
    @Log(title = "意向客户", businessType = BusinessType.OTHER)
    @ApiOperation(value = "重新校验",notes = "爬虫按钮")
    @PreAuthorize("@ss.hasPermi('custom:info:reptilallchick')")
    public R reptilallchick(@RequestBody ReptileFrom reptileFrom){
        reptileFrom.setReptileType("reptilallchick");
        return iCrmCustomerUserService.reptile(reptileFrom);
    }


    @GetMapping("/realTime/{customerId}")
    @Log(title = "计算统计", businessType = BusinessType.OTHER)
    @ApiOperation(value = "计算统计",notes = "计算统计")
    @PreAuthorize("@ss.hasPermi('custom:info:realTime')")
    public AjaxResult realTime (@PathVariable("customerId") Long customerId){
        return crmCustomerInfoService.realTime(customerId);
    }

}
